package bar.dark.lee.setting.data;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import bar.dark.lee.BDConstents;
import bar.dark.lee.IntroActivitiy;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.setting.TipInfoActivity;
import bar.dark.lee.setting.TipsActivity;

public class DataInActivity extends SuperActivity
{
	private ListView listView;
	private ImportDataAdapter adapter;
	private ArrayList<ImportData> list;
	
	private File [] readFiles;
	
	private File [] readAutoFiles;
	
	private ImportData data;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.data_in_activity);
		
		setTitle("데이터 복구");
		
		setFindView();
		setClickListener();
		new ShowDialog().execute(0);
	}

	private void setFindView()
	{
		listView = (ListView) findViewById(R.id.settingImportListView);
	}
	
	private void setClickListener()
	{
		listView.setOnItemClickListener(onItemClickListener);
	}
	
	private void setData()
	{
		list = new ArrayList<ImportData>();
		
		try
		{
			File directory = new File(Environment.getExternalStorageDirectory() + "/AccountBook/");
			
			readFiles = directory.listFiles(new FilenameFilter()
			{
				@Override
				public boolean accept(File dir, String filename)
				{
					return filename.endsWith(".db");
				}
			});
			
			File directory2 = new File(Environment.getExternalStorageDirectory() + "/AccountBook/Auto");
			
			readAutoFiles = directory2.listFiles(new FilenameFilter()
			{
				@Override
				public boolean accept(File dir, String filename)
				{
					return filename.endsWith(".db");
				}
			});
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3)
		{
			if (position >= list.size())
			{
				return;
			}
			
			data = null;
			data = list.get(position);
			
			AlertDialog.Builder dialog = new AlertDialog.Builder(DataInActivity.this);
			dialog.setTitle("데이터복구");
			dialog.setMessage("데이터 복구/삭제/메일전송 이 가능합니다.");
			
			dialog.setPositiveButton("복구", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					new ShowDialog().execute(1);
					dialog.dismiss();
				}
			});
			
			dialog.setNeutralButton("삭제", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					new ShowDialog().execute(2);
					dialog.dismiss();
				}
			});
			
			dialog.setNegativeButton("메일전송", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					Calendar calendar = Calendar.getInstance();
					String date = calendar.get(Calendar.YEAR) + "" + (calendar.get(Calendar.MONTH)+1) + "" + calendar.get(Calendar.DAY_OF_MONTH) + "";
					
					Intent i=new Intent(Intent.ACTION_SEND); 
					i.setType("plain/text");
					i.putExtra(Intent.EXTRA_SUBJECT, date + "-꿀꿀이가계부 백업파일"); 
					i.putExtra(Intent.EXTRA_TEXT, date + "-꿀꿀이가계부 백업파일 이메일 전송");
					
					String filePath = "";
					
					if (data.getAutoYN().equals("1"))
					{
						filePath = "/AccountBook/";
					}
					else
					{
						filePath = "/AccountBook/Auto/";
					}
					
					// 파일 첨부
					//i.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory() + filePath + data.getFileName()));
					i.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + Environment.getExternalStorageDirectory() + filePath + data.getFileName()));
					// 앱선택 박스를 띄움.
					//startActivity(Intent.createChooser(i, "How do you want to send message?"));
					//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					
					// com.google.android.gm 패키지의 ComposeActivityGmail 액티비티를 명시적으로 기입해도 될듯~!
					//i.setComponent(new ComponentName("com.google.android.gm","com.google.android.gm.ComposeActivity"));
					//startActivity(i);
					startActivity(Intent.createChooser(i, "꿀꿀이가계부 백업파일 전송"));
				}
			});
			
			dialog.show();
		}
	};
	
	private boolean setImportData(ImportData data)
	{
		DBSQLite.getInstance(this).closeDatabese();
		
		FileInputStream fis = null;
		FileOutputStream fos = null;
		
		try
		{
			fis = new FileInputStream(data.getData());
			
			File writeFile = new File("/data/data/" 
					+ getPackageName() + "/" 
					+ DBSQLite.dataBaseName);
			
			fos = new FileOutputStream(writeFile);
			
			byte [] buffer = new byte[1024];
			
			int bufBytes = 0;
			while ((bufBytes = fis.read(buffer)) != -1) 
			{
				fos.write(buffer, 0, bufBytes);
			}
			fos.flush();
			
		} catch (Exception e)
		{
			return false;
		} finally {
			try
			{
				if (fis != null) fis.close();
				if (fos != null) fos.close();
				DBSQLite.getInstance(this);
			} catch (IOException e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private boolean setImportDataDelete(ImportData data)
	{
		String filePath = "";
		
		if (data.getAutoYN().equals("1"))
		{
			filePath = "/AccountBook/";
		}
		else
		{
			filePath = "/AccountBook/Auto/";
		}
		
		File file = new File(Environment.getExternalStorageDirectory() + filePath + data.getFileName());
		
		if (file != null)
		{
			file.delete();
			return true;
		}
		
		return false;
	}
	
	private class ImportDataAdapter extends ArrayAdapter<ImportData>
	{
		public ImportDataAdapter(Context context, int textViewResourceId,
				ArrayList<ImportData> list)
		{
			super(context, textViewResourceId, list);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View v = convertView;
			
			if (v == null)
			{
				v = getLayoutInflater().inflate(R.layout.list_item_indata, null);
			}
			
			ImportData data = list.get(position);
			
			TextView name = (TextView) v.findViewById(R.id.listInData);
			name.setText(data.getFileName());
			
			return v;
		}
	}
	
	private class ImportData
	{
		private String fileName;
		private File data;
		private String autoYN;
		
		public String getFileName()
		{
			return fileName;
		}
		public void setFileName(String fileName)
		{
			this.fileName = fileName;
		}
		public File getData()
		{
			return data;
		}
		public void setData(File data)
		{
			this.data = data;
		}
		public String getAutoYN()
		{
			return autoYN;
		}
		public void setAutoYN(String autoYN)
		{
			this.autoYN = autoYN;
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		boolean flag = true;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(DataInActivity.this);
			dialog.setCancelable(false);
			dialog.setMessage("Loading...");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0)
			{
				setData();
				return 0;
			}
			else if (arg0[0] == 1)
			{
				flag = setImportData(data);
				return 1;
			}
			else if (arg0[0] == 2)
			{
				flag = setImportDataDelete(data);
				return 2;
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			dialog.dismiss();
			
			if (result == 0)
			{
				if (readFiles == null && readAutoFiles == null)
				{
					View resultNoView = getLayoutInflater().inflate(R.layout.view_no_result, null);
					listView.addHeaderView(resultNoView);
					adapter = new ImportDataAdapter(DataInActivity.this, R.layout.list_item_indata, list);
					listView.setAdapter(adapter);
					return;
				}
				else
				{
					if (readFiles != null)
					{
						for (int i = 0; i < readFiles.length; i++)
						{
							ImportData data = new ImportData();
							data.setFileName(readFiles[i].getName());
							data.setData(readFiles[i]);
							data.setAutoYN("1");
							list.add(data);
						}
					}
					
					if (readAutoFiles != null)
					{
						for (int i = 0; i < readAutoFiles.length; i++)
						{
							ImportData data = new ImportData();
							data.setFileName(readAutoFiles[i].getName());
							data.setData(readAutoFiles[i]);
							data.setAutoYN("0");
							list.add(data);
						}
					}
					
					adapter = new ImportDataAdapter(DataInActivity.this, R.layout.list_item_indata, list);
					listView.setAdapter(adapter);
					listView.setHeaderDividersEnabled(false);
					return;
				}
			}
			else if (result == 1)
			{
				if (flag)
				{
					SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
			       	SharedPreferences.Editor editor = pref.edit();
			       	
			       	editor.remove(BDConstents.NOTICE_FLAG);
			       	editor.commit();
					
					AlertDialog.Builder builder = new AlertDialog.Builder(DataInActivity.this);
					builder.setTitle("데이터복구");
					builder.setMessage("데이터 복구를 성공 하였습니다.");
					builder.setIcon(android.R.drawable.ic_dialog_info);
					builder.setNegativeButton("확인", new OnClickListener()
					{
						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							BDUtil.btnEnable = true;
							BDUtil.asyncFlag = 0;
							
							Intent intent = new Intent(DataInActivity.this, IntroActivitiy.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
							startActivity(intent);
							
							dialog.dismiss();
							finish();
						}
					});
					builder.setOnCancelListener(new OnCancelListener() {
						@Override
						public void onCancel(DialogInterface dialog) {
							BDUtil.btnEnable = true;
							BDUtil.asyncFlag = 0;
							
							Intent intent = new Intent(DataInActivity.this, IntroActivitiy.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
							startActivity(intent);
							
							dialog.dismiss();
						}
					});
					AlertDialog dialog = builder.create();
					dialog.show();
				}
				else if (!flag)
				{
					BDUtil.showDialog(DataInActivity.this, "데이터복구실패", "데이터 복구를 실패 하였습니다.");
				}
			}
			else if (result == 2)
			{
				if (flag)
				{
					BDUtil.showDialog(DataInActivity.this, "데이터삭제", "데이터가 목록에서 삭제 되었습니다.");
					
					new ShowDialog().execute(0);
				}
				else if (!flag)
				{
					BDUtil.showDialog(DataInActivity.this, "확인", "데이터 삭제를 실패 하였습니다.");
				}
			}
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(this, TipInfoActivity.class);
		intent.putExtra(TipsActivity.TIP_REQUEST_KEY, TipsActivity.TIP_DATABANKUP);
		startActivity(intent);
	}
}
